/**
 *
 */
package com.ybkj.daijia.api.driver.v1;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OrderAcceptEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverConsumedRecord;
import com.ybkj.daijia.server.model.DriverRechargeRecord;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.OrderGroup;
import com.ybkj.daijia.server.model.OrderStatus;
import com.ybkj.daijia.server.model.OrderStatus.StatusType;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverConsumedRecordService;
import com.ybkj.daijia.server.service.DriverRechargeRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FinancialRecordService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderGroupService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.OrderStatusService;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller
@RequestMapping(value = "driver/api/rest/v1")
public class ProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderGroupService orderGroupService;

    @Autowired
    private OrderStatusService orderStatusService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private FinancialRecordService financialRecordService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private DriverApplyService driverApplyService;

    @Autowired
    private DriverRechargeRecordService driverRechargeRecordService;

    @Autowired
    private DriverConsumedRecordService driverConsumedRecordService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    /**
     * 查询新工单，即服务人员还未接收的单
     * @param driverID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "findNewTask")
    public @ResponseBody
    ResultTransport findNewTask(Long driverID, String appKey, String token, String timestamp) {

        logger.debug("recv driverID:{},appKey:{},token:{},timestamp:{}", driverID, appKey, token,
            timestamp);

        if (null == driverID || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            List<Order> orders = orderService
                .findByDriverAndStatus(driver, Order.ORDER_STATUS_YIPAIDAN); //已经把单派给了服务人员
            if (CollectionUtils.isNotEmpty(orders)) {
                for (Order order : orders) {
                    Company thisCompany = companyService.findOne(order.getCompanyId());
                    if (null != thisCompany) {
                        Passenger passenger = memberService.findOnePassenger(order.getClientId());
                        if (null != passenger) {
                            Area daijiaArea = null;
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                daijiaArea = areaService
                                    .findDaijiaByEnterprise(passenger.getEnterprise_id());
                            }

                            if (null != daijiaArea) {
                                thisCompany
                                    .setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                            } else {
                                thisCompany.setArea(
                                    areaService.findOneWithCharge(thisCompany.getAreaId()));
                            }
                        } else {
                            thisCompany
                                .setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                        }
                    }
                    order.setCompany(thisCompany);
                }
            }

            ResultTransport tran = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            tran.setData(orders);

            return tran;

        } catch (Exception e) {
            logger.error("api v1 driver findNewTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 服务人员拒单
     * @param driverID
     * @param orderID
     * @param content
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "cancelTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport cancelTask(Long driverID, Long orderID, String content, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},orderID:{},content:{},appKey:{},token:{},timestamp:{}",
            driverID, orderID, content, appKey, token, timestamp);

        if (null == driverID || null == orderID || StringUtils.isBlank(content) || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (content.length() > 255) {
            return ResultTransport.getErrorBy(ErrorConstant.CONTENT_TOO_LONG);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(orderID));
        params.add(content);
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowDriverCancel()) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_CANNOT_CANCEL_ORDER);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            Order order = orderService.findOne(orderID);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (Order.ORDER_STATUS_BUSY != order.getStatus()) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
            }

            if (!order.getDriverId().equals(driverID)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            orderService.driverCancel(order, content);

            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //服务人员销单成功

        } catch (Exception e) {
            logger.error("api v1 driver cancelTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 申请销单
     * @param driverID
     * @param orderID
     * @param content
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "refuseTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport refuseTask(Long driverID, Long orderID, String content, String appKey,
        String token, String timestamp) {

        logger
            .debug("recv driverID:{},orderID:{},appKey:{},token:{},timestamp:{}", driverID, orderID,
                appKey, token, timestamp);

        if (null == driverID || null == orderID || StringUtils.isBlank(content) || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(orderID));
        params.add(content);
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            Order order = orderService.findOne(orderID);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (Order.ORDER_STATUS_YIPAIDAN != order.getStatus()) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
            }

            if (!order.getDriverId().equals(driverID)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            orderService.refuse(order, content);

            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //申请销单成功

        } catch (Exception e) {
            logger.error("api v1 driver refuseTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 接受工单
     * @param driverID
     * @param orderID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "acceptTask", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport acceptTask(Long driverID, Long orderID, String appKey, String token,
        String timestamp) {

        logger
            .debug("recv driverID:{},orderID:{},appKey:{},token:{},timestamp:{}", driverID, orderID,
                appKey, token, timestamp);

        if (null == driverID || null == orderID || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(orderID));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            if (driver.getIsFreeze()) {
                return ResultTransport.getErrorBy(ErrorConstant.USER_IS_FREEZE_ERROR);
            }

            Order order = orderService.findOne(orderID);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (Order.ORDER_STATUS_YIPAIDAN != order.getStatus()) {
                ResultTransport instance = ResultTransport
                    .getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
                instance.setData(order);
                return instance;
            }

            if (!order.getDriverId().equals(driverID)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            int status = orderService.accept(order, driver);

            if (status == -1) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            //接受工单事件
            OrderAcceptEvent acceptEvent = new OrderAcceptEvent(order);
            applicationEventMulticaster.multicastEvent(acceptEvent);

            Company thisCompany = companyService.findOne(order.getCompanyId());
            if (null != thisCompany) {
                Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
                if (null != passenger) {
                    Area daijiaArea = null;
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        daijiaArea = areaService
                            .findDaijiaByEnterprise(passenger.getEnterprise_id());
                    }

                    if (null != daijiaArea) {
                        thisCompany.setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                    } else {
                        thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                    }
                } else {
                    thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                }
            }
            order.setCompany(thisCompany);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //接单成功
            instance.setData(order);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver acceptTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    /**
     * 报单
     * @param driverID
     * @param xml
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "reportTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport reportTask(Long driverID, String xml, String appKey, String token,
        String timestamp) {

        logger
            .debug("recv driverID:{},xml:{},appKey:{},token:{},timestamp:{}", driverID, xml, appKey,
                token, timestamp);

        if (null == driverID || StringUtils.isBlank(xml) || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(xml);
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            boolean flag = orderService.report(driver, xml);
            if (flag) {
                return ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            }

            return ResultTransport.getErrorBy(ErrorConstant.REPORT_XML_ERROR);

        } catch (Exception e) {
            logger.error("api v1 driver reportTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


    /**
     * 服务人员到达客户预约地开始计时
     * @param driverID
     * @param orderID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "arrivePlace", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport arrivePlace(Long driverID, Long orderID, Long arriveTime, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverID:{},orderID:{},arriveTime:{},appKey:{},token:{},timestamp:{}",
            driverID, orderID, arriveTime, appKey, token, timestamp);

        if (null == driverID || null == orderID || null == arriveTime || 0 == arriveTime
            || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(orderID));
        params.add(String.valueOf(arriveTime));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            Order order = orderService.findOne(orderID);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (Order.ORDER_STATUS_BUSY != order.getStatus()) {
                ResultTransport instance = ResultTransport
                    .getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
                instance.setData(order);
                return instance;
            }

            List<OrderStatus> statuslist = orderStatusService.findByOrder(order.getId());
            OrderStatus acceptStatus = null;
            if (CollectionUtils.isNotEmpty(statuslist)) {
                Collections.sort(statuslist, new Comparator<OrderStatus>() {
                    public int compare(OrderStatus arg0, OrderStatus arg1) {
                        return arg1.getId().compareTo(arg0.getId());
                    }
                });
                acceptStatus = statuslist.get(0);
            }
            if (null != acceptStatus && !acceptStatus.getStatusType().equals(StatusType.accept)) {
                ResultTransport instance = ResultTransport
                    .getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
                instance.setData(order);
                return instance;
            }

//			order.setOrderStatuss(orderStatusService.findByOrder(order.getId()));
//			if(null!=order.getDaokehuTime()){
//				logger.debug("已经等待过");
//				ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
//				instance.setData(order);
//				return instance;
//			}

            if (!order.getDriverId().equals(driverID)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            orderService.arrivePlace(order, new Date(arriveTime));

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(order);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver arrivePlace error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 服务人员等待结束开始代驾
     * @param driverID
     * @param orderID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "startDrive", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport startDrive(
        Long driverID, Long orderID, Double driverLongitude, Double driverLatitude,
        Long arriveTime, Long startDriveTime,
        String toPlace, Double toPlaceLongitude, Double toPlaceLatitude,
        String isWannaWc, Long workCarTime,
        String appKey, String token, String timestamp) {

        logger.debug(
            "recv driverID:{},orderID:{},driverLongitude:{},driverLatitude:{},arriveTime:{},startDriveTime:{},toPlace:{},toPlaceLongitude:{},toPlaceLatitude:{},isWannaWc:{},workCarTime:{},appKey:{},token:{},timestamp:{}",
            driverID, orderID, driverLongitude, driverLatitude, arriveTime, startDriveTime, toPlace,
            toPlaceLongitude, toPlaceLatitude, isWannaWc, workCarTime, appKey, token, timestamp);

        if (null == driverID || null == orderID || null == arriveTime || 0 == arriveTime ||
            null == startDriveTime || 0 == startDriveTime || StringUtils.isBlank(isWannaWc) ||
            SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverID));
        params.add(String.valueOf(orderID));
        params.add(String.valueOf(driverLongitude));
        params.add(String.valueOf(driverLatitude));
        params.add(String.valueOf(arriveTime));
        params.add(String.valueOf(startDriveTime));
        params.add(String.valueOf(toPlace));
        params.add(String.valueOf(toPlaceLongitude));
        params.add(String.valueOf(toPlaceLatitude));
        params.add(String.valueOf(isWannaWc));
        params.add(String.valueOf(workCarTime));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverID);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            Order order = orderService.findOne(orderID);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
                if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                    return ResultTransport.getErrorBy(ErrorConstant.ORDER_HASBEEN_REVOKE);
                } else if (order.getStatus().equals(Order.ORDER_STATUS_CANCELED)) {
                    return ResultTransport.getErrorBy(ErrorConstant.ORDER_HASBEEN_CANCEL);
                } else {
                    return ResultTransport.getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
                }
            }
            order.setOrderStatuss(orderStatusService.findByOrder(order.getId()));

            if (!order.getDriverId().equals(driverID)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            //如果请求接
            if (isWannaWc.equals("1")) {
                if (null == workCarTime || 0 == workCarTime || StringUtils.isBlank(toPlace)) {
                    logger.debug("请求接参数错误");
                    return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
                }
                if (null == toPlaceLongitude || -1 == toPlaceLongitude || null == toPlaceLatitude
                    || -1 == toPlaceLatitude) {
                    toPlaceLongitude = driver.getLongitude();
                    toPlaceLatitude = driver.getLatitude();
//					Result<Map<String, Double>> result = HttpClientUtil.getLngAndLatByPlace(toPlace, driver.getCompany().getArea().getName());
//					if(result.isSuccess()){
//						Map<String, Double> map=result.getResult();
//						toPlaceLongitude=map.get("lng");
//						toPlaceLatitude=map.get("lat");
//						if(null==toPlaceLongitude || -1==toPlaceLongitude || null==toPlaceLatitude || -1==toPlaceLatitude){
//							return ResultTransport.getErrorBy(ErrorConstant.ADDRESS_ERROR);
//						}
//					}
//					else{
//						logger.debug("toPlace:"+toPlace+"---------city:"+driver.getCompany().getArea().getName());
//						return ResultTransport.getErrorBy(ErrorConstant.ADDRESS_ERROR);
//					}
                }
            }

            if (StringUtils.isNotBlank(toPlace)) {
                order.setToPlace(toPlace);
            }
            if (null != toPlaceLongitude && toPlaceLongitude != -1) {
                order.setToPlaceLongitude(toPlaceLongitude);
            }
            if (null != toPlaceLatitude && toPlaceLatitude != -1) {
                order.setToPlaceLatitude(toPlaceLatitude);
            }

            if (null != driverLongitude && driverLongitude != -1) {
                driver.setLongitude(driverLongitude);
            }
            if (null != driverLatitude && driverLatitude != -1) {
                driver.setLatitude(driverLatitude);
            }

            orderService.startDrive(order, new Date(arriveTime), new Date(startDriveTime), driver,
                isWannaWc, workCarTime, null);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(order);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver startDrive error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 查询抢单
     * @param longitude
     * @param latitude
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "rushOrder", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport rushOrder(Long driverId, Double longitude, Double latitude,
        String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},longitude:{},latitude:{},appKey:{},token:{},timestamp:{}",
            driverId, longitude, latitude, appKey, token, timestamp);

        if (null == driverId || null == longitude || null == latitude || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(longitude));
        params.add(String.valueOf(latitude));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowRushOrder()) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_RUSH_CANCELED);
        }

        Driver driver = driverService.findOne(driverId);
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        try {

            List<Order> list = orderService.rushOrder(longitude, latitude, driver);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Order order : list) {
                    Company thisCompany = companyService.findOne(order.getCompanyId());
                    if (null != thisCompany) {
                        Passenger passenger = memberService.findOnePassenger(order.getClientId());
                        if (null != passenger) {
                            Area daijiaArea = null;
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                daijiaArea = areaService
                                    .findDaijiaByEnterprise(passenger.getEnterprise_id());
                            }

                            if (null != daijiaArea) {
                                thisCompany
                                    .setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                            } else {
                                thisCompany.setArea(
                                    areaService.findOneWithCharge(thisCompany.getAreaId()));
                            }
                        } else {
                            thisCompany
                                .setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                        }
                    }
                    order.setCompany(thisCompany);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(list);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver rushOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 提交抢单
     * @param driverId
     * @param orderId
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "getRushOrder", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport getRushOrder(Long driverId, Long orderId,
        String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},orderId:{},appKey:{},token:{},timestamp:{}",
            driverId, orderId, appKey, token, timestamp);

        if (null == driverId || null == orderId || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(orderId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowRushOrder()) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_RUSH_CANCELED);
        }

        Driver driver = driverService.findOne(driverId);
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstant.USER_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(new Error(-27, "您还未上线，不能抢单"));
            } else if (driver.getStatus().equals(Driver.DRIVER_APPLY_ORDER) || driver.getStatus()
                .equals(Driver.DRIVER_BUSY)) {
                return ResultTransport.getErrorBy(new Error(-27, "您有未完成的工单，不能抢单"));
            }
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_STATUS_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_HASBEEN_RUSHED);
        }

        if (!driver.getDriverJobType().equals(Driver.DriverJobType.all)) {
            if (!driver.getDriverJobType().contains(Driver.DriverJobType.daijia.toString())) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_IS_DAIJIA_ERROR);
            }
        }

        try {

            orderService.getRushOrder(driver, order);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            Company thisCompany = companyService.findOne(order.getCompanyId());
            if (null != thisCompany) {
                Passenger passenger = memberService.findOnePassenger(order.getClientId());
                if (null != passenger) {
                    Area daijiaArea = null;
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        daijiaArea = areaService
                            .findDaijiaByEnterprise(passenger.getEnterprise_id());
                    }

                    if (null != daijiaArea) {
                        thisCompany.setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                    } else {
                        thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                    }
                } else {
                    thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                }
            }
            order.setCompany(thisCompany);
            instance.setData(order);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver getRushOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 获取客户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getMemberInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getMemberInfo(String phone, String appKey, String token, String timestamp) {

        logger.debug("recv phone:{},appKey:{},token:{},timestamp:{}", phone, appKey, token,
            timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
        }

        try {

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(passenger);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver getMemberInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "getMemberAccountInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getMemberAccountInfo(String phone, String appKey, String token,
        String timestamp) {

        logger.debug("recv phone:{},appKey:{},token:{},timestamp:{}", phone, appKey, token,
            timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
        }

        try {

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            PassengerAddress passengerAddress = memberService
                .findUsuallyAddress(passenger.getId(), PassengerAddress.TYPE_ADDRESS_OTHER);
            Map<String, Object> map = new HashMap<String, Object>();
            if (null != passengerAddress) {
                map.put("address", passengerAddress.getAddress());
                map.put("addressLng", passengerAddress.getLongitude());
                map.put("addressLat", passengerAddress.getLatitude());
            } else {
                map.put("address", null);
                map.put("addressLng", null);
                map.put("addressLat", null);
            }

            instance.setData(map);
            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver getMemberAccountInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 获取订单信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getOrderInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getOrderInfo(Long orderId, String appKey, String token, String timestamp) {

        logger.debug("recv orderId:{},appKey:{},token:{},timestamp:{}", orderId, appKey, token,
            timestamp);

        if (null == orderId || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(orderId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            Company thisCompany = companyService.findOne(order.getCompanyId());
            if (null != thisCompany) {
                Passenger passenger = memberService.findOnePassenger(order.getClientId());
                if (null != passenger) {
                    Area daijiaArea = null;
                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                        daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        daijiaArea = areaService
                            .findDaijiaByEnterprise(passenger.getEnterprise_id());
                    }

                    if (null != daijiaArea) {
                        thisCompany.setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                    } else {
                        thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                    }
                } else {
                    thisCompany.setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                }
            }
            order.setCompany(thisCompany);

            //订单分组
            if (null != order.getOrderGroupId()) {
                OrderGroup orderGroup = orderGroupService.findOne(order.getOrderGroupId());
                if (null != orderGroup && null != orderGroup.getDriverId() && !orderGroup
                    .getDriverId().equals(order.getDriverId())) {
                    Driver jiedanDriver = driverService.findOne(orderGroup.getDriverId());
                    order.setClientPhone(jiedanDriver.getPhone());
                    order.setUserPhone(jiedanDriver.getPhone());
                }
            }

            instance.setData(order);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver getOrderInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 获取客户常用目的地
     * @param phone
     * @return
     */
    @RequestMapping(value = "getUsuallyToplace", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getUsuallyToplace(String phone, String appKey, String token, String timestamp) {

        logger.debug("recv phone:{},appKey:{},token:{},timestamp:{}", phone, appKey, token,
            timestamp);

        if (StringUtils.isBlank(phone) || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(phone));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
        }

        try {
            PassengerAddress passengerAddress = memberService
                .findUsuallyAddress(passenger.getId(), PassengerAddress.TYPE_ADDRESS_OTHER);
            Map<String, Object> map = new HashMap<String, Object>();
            if (null != passengerAddress) {
                map.put("result", Boolean.TRUE);
                map.put("address", passengerAddress.getAddress());
                map.put("lng", passengerAddress.getLongitude());
                map.put("lat", passengerAddress.getLatitude());
            } else {
                map.put("result", Boolean.FALSE);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver getUsuallyToplace error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 获取服务人员充值记录
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "rechargeRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport rechargeRecord(Long driverId, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverId:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverId,
            page, limit, appKey, token, timestamp);

        if (driverId == null || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Driver driver = driverService.findOne(driverId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        try {

            Page<DriverRechargeRecord> records = driverRechargeRecordService
                .rechargeRecord(driverId, page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(records);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver rechargeRecord error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 获取服务人员消费记录
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "consumedRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport consumedRecord(Long driverId, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv driverId:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", driverId,
            page, limit, appKey, token, timestamp);

        if (driverId == null || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Driver driver = driverService.findOne(driverId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        try {

            Page<DriverConsumedRecord> records = driverConsumedRecordService
                .consumedRecord(driverId, page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(records);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver consumedRecord error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

}
